import React, { Component } from 'react';
import { Tree, Button, Select, Feedback } from '@icedesign/base';
import IceContainer from '@icedesign/container';
import axios from 'axios';
import {hashHistory} from 'react-router';
import Config from '../../../../utils/Config';
import {GET,POST,PUT} from '../../../../utils/public'
import './RoleList.scss';

const { Option } = Select;
const { Node: TreeNode } = Tree;
export default class RoleList extends Component {
  static displayName = 'RoleList';

  static propTypes = {};

  static defaultProps = {};

  constructor(props) {
    super(props);
    this.state = {
      treeData:[],
      keyData:[],
      expandedKeys: [],
      checkedKeys: [],
      type:null,
      code:null,
      checkStrictly:true,      
      autoExpandParent: true,
    };
    this.handleCheck = this.handleCheck.bind(this);
    
  }

  // ICE: React Component 的生命周期

  componentWillMount() {}

  componentDidMount() {
    let roleId= this.props.roleId; // 当前节点code
    let type = this.props.type;//打开窗口类型 add为添加权限
     

    //新增角色url
    let add_url = 'api/permissions/tree'
    //编辑角色
    let edit_url = 'api/permissions/tree?id='
    let url = (type=='add')?add_url:edit_url;
    //console.log(url)
    const matchedKeys = []; //节点数组，填充expandedkeys，展开所有节点
    const checkKeys = []; //checked节点数组，改变节点的选中状态

    //请求角色权限树
    const arr = [];
    GET(url)
      .then(res=>{
        if(!res){
          Feedback.toast.error('与服务器失去连接，稍后再试！')
          return
        }else{
          console.log(res)
        }
      })
    axios.get(url).then((response) => {
      if(response.data.success){
        let res = response.data.data[0];
        arr.push({id: res.id,text:'权限管理',disabled:true,data:{id:res.data.id},children:res.children}) //去除根节点，并保留其id
       
        this.setState({treeData:arr});
        loopKeys(arr)
        this.setState({
          checkedKeys: checkKeys,
          expandedKeys: matchedKeys,
          autoExpandParent: true
        });
      }else{
        if(response.data.code == 401 && response.data.msg== '请登录!'){
          Feedback.toast.error(response.data.msg);
          setTimeout(()=>{
            hashHistory.push('/login');
          },3000) 
        }else{
          Feedback.toast.error(response.data.msg);
        }
        return ;
        //this.setState({treeData:[]}); 
      } 
    }).catch((error)=>{
      Feedback.toast.error('数据读取失败，稍后再试！');
      return;
    });;
    //取出所有节点keys值，展开所有节点
    const loopKeys = data =>
    data.forEach(item => {
      if (item.id) {
        matchedKeys.push(item.id+'code'+item.data.id);
      }
      if(item.checked){
        checkKeys.push(item.id+'code'+item.data.id)
      }
      if (item.children && item.children.length) {
        loopKeys(item.children);
      }
    });
  }

  componentWillUnmount() {

  }

  handleCheck(keys, info){
    console.log(keys)
    this.setState({
      checkedKeys: keys
    });
    let keyCode = ''; //当前节点的id 即code
    let keyId = '';   //当前节点的data.id
    let Ids = [];     //为角色分配的权限的 id数组
    keys.forEach(item=>{
      keyCode = item.split('code')[0];
      keyId = item.split('code')[1];
      Ids.push({"id":keyId})
    })
    var newState = {
      id:[]
    }
    newState.id = Ids
    this.props.onChange(newState)   //回掉函数传递参数给父组件 addRolesDialog
  };


  render() {
    // this.setState({code:this.props.code,type:this.props.type});
    // console.log(this.state.code+','+this.state.type)
    const loop = data =>
    data.map(item => {
      return (
        //key值格式  code+"code"+id
          <TreeNode label={item.text} key={item.id+'code'+item.data.id} disabled={item.disabled} >
            {item.children && item.children.length ? loop(item.children) : null}
          </TreeNode>  
      );
    });
    return (
      
        <IceContainer>
           <Tree
          editable
          checkable
          showLine
          checkedKeys={this.state.checkedKeys}
          onCheck={this.handleCheck}
          expandedKeys={this.state.expandedKeys}
          autoExpandParent={this.state.autoExpandParent}
        >
        {loop(this.state.treeData)}
        </Tree>
        </IceContainer>
    );
  }
}

